import http from '@/utils/http'
import { isLoggedIn } from '@/utils/auth'
import { ElMessage } from 'element-plus'

export const textDisplayMixin = {
  data() {
    return {
      loggedIn: false,
      loading: true,
      selectedWordIndices: { sentenceIndex: -1, wordIndex: -1 },
      markingAllAsMastered: false,
      ieltsWords: [],
      showWordDetailDialog: false,
      selectedWord: null,
      showIELTSWords: false,
      showChieses: true,
      showDifficultWords: true
    }
  },
  
  methods: {
    getOptsFromLocalStorage() {
      this.showChieses = localStorage.getItem('showChieses') !== 'false';
      this.showIELTSWords = localStorage.getItem('showIELTSWords') === 'true';
      this.showDifficultWords = localStorage.getItem('showDifficultWords') === 'true';
    },
    
    writeOptsToLocalStorage() {
      localStorage.setItem('showChieses', this.showChieses);
      localStorage.setItem('showIELTSWords', this.showIELTSWords);
      localStorage.setItem('showDifficultWords', this.showDifficultWords);
    },
    
    splitSentence(sentence) {
      // Split sentence into words while preserving spaces and punctuation
      return sentence.split(/(\s+)/).filter(token => token.trim() !== '');
    },
    
    toggleShowChinese() {
      this.showChieses = !this.showChieses;
      this.writeOptsToLocalStorage();
    },
    
    toggleIELTSWords() {
      this.showIELTSWords = !this.showIELTSWords;
      this.writeOptsToLocalStorage();
    },
    
    toggleDifficultWords() {
      this.showDifficultWords = !this.showDifficultWords;
      this.writeOptsToLocalStorage();
    },
    
    isIeltsWord(word) {
      // 检查单词是否为IELTS单词
      const cleanWord = word.replace(/[^\w]/g, '').toLowerCase();
      return this.showIELTSWords && this.ieltsWords.includes(cleanWord);
    },

    isDifficultWord(word) {
      // 检查单词是否为生词
      const cleanWord = word.replace(/[^\w]/g, '').toLowerCase();
      return this.showDifficultWords && this.markedWords.some(item => item.word === cleanWord);
    },

    async loadIeltsWords() {
      // 加载IELTS单词
      if (!this.courseId || !this.lessonId) return;

      try {
        const response = await http.get(`/vocabulary/ielts/${this.courseId}/${this.lessonId}`);
        this.ieltsWords = response;
      } catch (error) {
        console.error('Error loading IELTS words:', error);
      }
    },

    showWordDetail(word) {
      // Clean up the word (remove surrounding punctuation)
      const cleanWord = word.replace(/^[^\w]+|[^\w]+$/g, '').toLowerCase();
      if (!cleanWord) return;

      this.selectedWord = {
        vocabulary: cleanWord
      };
      this.showWordDetailDialog = true;
    },

    closeWordDetail() {
      this.showWordDetailDialog = false;
      this.selectedWord = null;
    },

    // 处理单词标记/取消标记
    handleToggleWordMark(wordData) {
      this.$emit('toggle-word-mark', wordData);
    },

    // 检查单词是否已被标记为生词
    isWordMarked(word) {
      if (!word || !this.markedWords) return false;
      const result = this.markedWords.find(item => item.word === word);
      return result && result.word ? true : false;
    },

    // 切换句子掌握状态
    toggleSentenceMastered(sentenceIndex) {
      this.$emit('toggle-sentence-mastered', sentenceIndex);
    },

    // 检查句子是否已掌握
    isSentenceMastered(sentenceIndex) {
      return this.masteredSentences.includes(sentenceIndex);
    },

    // 标记所有句子为已掌握
    async markAllSentencesAsMastered() {
      this.markingAllAsMastered = true;
      try {
        for (let i = 0; i < this.content.length; i++) {
          if (!this.isSentenceMastered(i)) {
            this.$emit('toggle-sentence-mastered', i);
            await new Promise(resolve => setTimeout(resolve, 50));
          }
        }
        ElMessage.success('已将所有句子标记为已掌握');
      } catch (error) {
        console.error('Error marking all sentences as mastered:', error);
        ElMessage.error('标记所有句子为已掌握时出错');
      } finally {
        this.markingAllAsMastered = false;
      }
    }
  },

  mounted() {
    // 添加滚动事件监听器，滚动时关闭所有popover
    this.loading = false;
    this.loggedIn = isLoggedIn();

    // 加载IELTS单词
    this.loadIeltsWords();
    this.getOptsFromLocalStorage();
  }
}